﻿using System;
using System.Linq;
using System.Reflection.Emit;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder
{
    internal sealed class SwitchTranslator : ITranslator
    {
        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction)
        {
            if(instruction.Inst != OpCodes.Switch)
            {
                throw new ArgumentException("instruction");
            }
            IVariable source = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            string[] targets = instruction.SwitchTargets
                .Select(msilTarget => methodBody.BasicBlocks
                    .First(cBlock => cBlock.MsilBlock == msilTarget).Label).ToArray();
            SwitchStatement stm = new SwitchStatement(targets, source);
            currentBlock.Statements.Add(stm);
            return stm;
        }
    }
}
